﻿<template>
  <a-modal
    :title="title"
    width="80%"
    :visible="visible"
    :confirmLoading="loading"
    @ok="handleSubmit"
    @cancel="
      () => {
        this.visible = false
      }
    "
  >
    <a-spin :spinning="loading">
      <a-form-model ref="form" :model="entity" :rules="rules" v-bind="layout">
        <a-collapse accordion default-active-key="1" :bordered="false" v-model="activeKey">
          <a-collapse-panel :style="customStyle" key="1" header="渠道商基本信息">
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="上级代理商" prop="SuperiorAgentID">
                  <a-select show-search option-filter-prop="children" v-model="entity.SuperiorAgentID" :filter-option="filterOption">
                    <a-select-option v-for="(item, index) in AgentList" :key="index" :value="item.Id">
                      {{ item.AgentName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="商务经理名称" prop="customerManagerId">
                  <a-select show-search option-filter-prop="children" v-model="entity.customerManagerId" :filter-option="filterOption">
                    <a-select-option v-for="(item, index) in UserList" :key="index">
                      {{ item.UserName }}
                    </a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="代理商" prop="AgentName">
                  <a-input v-model="entity.AgentName" autocomplete="off" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="统一信用代码" prop="USCC">
                  <a-input v-model="entity.USCC" autocomplete="off" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="地址" prop="Address">
                  <a-input v-model="entity.Address" autocomplete="off" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="法人" prop="LegalPersonName">
                  <a-input v-model="entity.LegalPersonName" autocomplete="off" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="营业执照号或身份证" prop="IdNumber">
                  <a-input v-model="entity.IdNumber" autocomplete="off" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="联系人" prop="ContactName">
                  <a-input v-model="entity.ContactName" autocomplete="off" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="电话" prop="Phone">
                  <a-input v-model="entity.Phone" autocomplete="off" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="所属地区" prop="Region">
                  <a-input v-model="entity.Region" autocomplete="off" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="银行账号" prop="SettlementAccount">
                  <a-input v-model="entity.SettlementAccount" autocomplete="off" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="开户银行" prop="SettlementBank">
                  <a-input v-model="entity.SettlementBank" autocomplete="off" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="预留手机号" prop="ReservedPhone">
                  <a-input v-model="entity.ReservedPhone" autocomplete="off" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="服务费率(%)" prop="Rate">
                  <a-input v-model="entity.Rate" autocomplete="off" />
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="佣金结算周期" prop="SettlementInterval">
                  <a-radio-group v-model="entity.SettlementInterval">
                    <a-radio-button value="10"> T+1结算 </a-radio-button>
                    <a-radio-button value="0"> 当月结算 </a-radio-button>
                    <a-radio-button value="1"> 次月结算 </a-radio-button>
                    <a-radio-button value="2"> 次次月结算 </a-radio-button>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="审核状态" prop="CheckStatus">
                  <a-radio-group v-model="entity.CheckStatus">
                    <a-radio-button value="0"> 待审核 </a-radio-button>
                    <a-radio-button value="1"> 审核通过 </a-radio-button>
                    <a-radio-button value="2"> 审核未通过 </a-radio-button>
                  </a-radio-group>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <a-collapse-panel :style="customStyle" key="2" header="证照资料">
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="证照资料">
                  <a-upload
                    list-type="picture-card"
                    :file-list="fileList"
                    @preview="handlePreview"
                    :remove="removefile"
                    :customRequest="selfUpload"
                    :before-upload="beforeUpload"
                  >
                    <div v-if="fileList.length < 5">
                      <a-icon type="plus" />
                      <div class="ant-upload-text">上传</div>
                    </div>
                  </a-upload>
                  <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
                    <img alt="example" style="width: 100%" :src="previewImage" />
                  </a-modal>
                </a-form-model-item>
              </a-col>
            </a-row>
            <a-row>
              <a-col :span="12">
                <a-form-model-item label="入网表格">
                  <a-button v-if="entity.attfile" @click="btn_downfile">下载文件</a-button>
                  <a-upload-dragger
                  v-else
                    name="file"
                    :before-upload="beforeUpload1"
                    :multiple="true"
                    :customRequest="selfUpload1"
                    @change="handleChange1"

                  >
                    <p class="ant-upload-drag-icon">
                      <a-icon type="inbox" />
                    </p>
                    <p class="ant-upload-text">单击或拖动文件到此区域</p>
                  </a-upload-dragger>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
        </a-collapse>
      </a-form-model>
    </a-spin>
  </a-modal>
</template>

<script>
function getBase64(img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
import OperatorCache from '@/utils/cache/OperatorCache'
export default {
  props: {
    parentObj: Object,
  },
  data() {
    return {
      fileList: [],
      previewVisible: false,
      previewImage: '',
      customStyle: 'background: #f7f7f7;border-radius: 4px;margin-bottom: 24px;border: 0;overflow: hidden',
      layout: {
        labelCol: { span: 5 },
        wrapperCol: { span: 18 },
      },
      visible: false,
      loading: false,
      entity: {},
      rules: {
        SuperiorAgentID:[{ required: true, message: '请选择上级代理商' }],
        customerManagerId:[{ required: true, message: '请选择商务经理' }],
        AgentName:[{ required: true, message: '请输入代理商名称' }],
        USCC:[{ required: true, message: '请输入统一信用代码' }],
        Address:[{ required: true, message: '请输入地址' }],
        areaName:[{ required: true, message: '请输入企业联系地址' }],
        IdNumber:[{ required: true, message: '请输入营业执照号或身份证' }],
        ContactName:[{ required: true, message: '请输入联系人' }],
        Phone:[{ required: true, message: '请输入联系电话' }],
        Region:[{ required: true, message: '请输入所属地区' }],
        SettlementAccount:[{ required: true, message: '请输入银行账号' }],
        SettlementBank:[{ required: true, message: '请输入开户银行' }],
        ReservedPhone:[{ required: true, message: '请输入预留手机号' }],
        Rate:[{ required: true, message: '请输入服务费率' }],
        SettlementInterval:[{ required: true, message: '请选择佣金周期' }],
        Rate:[{ required: true, message: '请输入服务费率' }],
      },
      imageUrl: '',
      title: '',
      Id:"",
      activeKey: ['1'], //折叠面板
      AgentList:[],
      UserList:[],
    }
  },
  methods: {
    btn_downfile(){
      console.log(this.entity.attfile)
      let index = this.entity.attfile.lastIndexOf("Upload")
      let spl = this.entity.attfile.substr(index)
      console.log(spl)
          this.$http.post('/Base_Manage/Upload/downSign',{id:spl},{responseType: 'blob'}).then(res =>{
          const blob = new Blob([res]);
          const fileName = "入网表格.xlsx";
          const elink = document.createElement('a');// 创建a标签
          elink.download = fileName;// 为a标签添加download属性
          // a.download = fileName; //命名下载名称
          elink.style.display = 'none';
          elink.href = URL.createObjectURL(blob);
          document.body.appendChild(elink);
          elink.click();// 点击下载
          URL.revokeObjectURL(elink.href); // 释放URL 对象
          document.body.removeChild(elink);// 释放标签
      })
    },
    removefile(file){
      console.log(file)
      let ids = [file.uid]
      // ids.push()
      this.$http.post('/Base_leasesystem_agent_img/leasesystem_agent_img/DeleteData', ids).then((res)=>{
        if(res.Success){
          this.GetAgentImg()
          this.$message.success("操作成功")
        }else{
          this.$message.error("操作失败")
        }
      })
    },
    init() {
      this.visible = true
      this.entity = {}
      this.$nextTick(() => {
        this.$refs['form'].clearValidate()
      })
    },
    GetAgentImg(){
      this.fileList = []
      let temp = {}
        temp.condition = "AID"
        temp.keyword = this.Id
         
        this.$http.post("/Base_leasesystem_agent_img/leasesystem_agent_img/GetDataList",{Search: temp}).then((res)=>{
          for(let i=0;i<res.Data.length;i++)
          {
            let Tem = {}
            Tem.url =  res.Data[i].imgUrl
            Tem.uid =  res.Data[i].Id
            Tem.name =  res.Data[i].imgName
            Tem.status = "done"
            this.fileList.push(Tem)
          }
        })
    },
    openForm(id, title) {
      this.AgentList = [];
      this.UserList = [];
      //代理商下拉框
      this.$http.post("/Base_Manage/Home/GetAgent_Select").then((res)=>{
        this.AgentList = res.Data
      })
      
      //客户经理
      this.$http.post("/Base_Manage/Home/GetUser_Select","1").then((res)=>{
        
        this.UserList = res.Data
      })

      this.fileList = []
      this.init()

      if (id) {
        this.Id = id
        this.loading = true
        this.$http.post('/Base_leasesystem_agent/leasesystem_agent/GetTheData', { id: id }).then((resJson) => {
          this.loading = false

          this.entity = resJson.Data
        })
        this.GetAgentImg()
      }
    },
    handleSubmit() {
      if(this.entity.CheckStatus == null){
        this.entity.CheckStatus = 0
      }
      this.$refs['form'].validate((valid) => {
        if (!valid) {
          return
        }
        this.loading = true
        this.$http.post('/Base_leasesystem_agent/leasesystem_agent/SaveData', this.entity).then((resJson) => {
          this.loading = false
          if (resJson.Success) {
            for(let i=0;i<this.fileList.length;i++){
              let temp = {}
              temp.AID = resJson.Data
              temp.imgName = this.fileList[i].name
              temp.imgUrl = this.fileList[i].url
              this.$http.post("/Base_leasesystem_agent_img/leasesystem_agent_img/SaveData",temp)
            }

            this.$message.success('操作成功!')
            this.visible = false

            this.parentObj.getDataList()
          } else {
            this.$message.error(resJson.Msg)
          }
        })
      })
    },
    filterOption(input, option) {
      return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    selfUpload({ action, file, onSuccess, onError, onProgress }) {
      this.loading = true
      console.log(action)
      const formData = new FormData()
      let that = this
      formData.append('file', file)
      // console.log(formData, 'formData')
      this.$http.post('/Base_Manage/Upload/UploadFileByForm', formData).then((res) => {
        var temp = {}
      temp.url = res.url
      temp.uid = this.fileList.length +1
      temp.name = res.name
      temp.status = res.status
      this.fileList.unshift(temp);
      this.loading = false
      })
    },
    selfUpload1({ action, file, onSuccess, onError, onProgress }) {
      this.loading = true
      const formData = new FormData()
      let that = this
      formData.append('file', file)
      this.$http.post('/Base_Manage/Upload/UploadFileByForm', formData).then((res) => {
        this.entity.attfile = res.url
        this.$message.success("上传成功")
        this.loading = false
      })
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 20
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJpgOrPng && isLt2M
    },
    beforeUpload1(file) {
      let fileType = file.name.split('.')
      const fileDate = fileType.slice(-1)
      if (['xlsx', 'xls', 'doc', 'docx', 'pdf'].indexOf(fileDate[0]) < 0) {
        this.$message.error('仅支持doc,docx,pdf,xls,xlsx 格式')
        return 
      }
    },
    handleChange1(info) {
      const status = info.file.status
      if (status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (status === 'done') {
        this.$message.success(`${info.file.name} file uploaded successfully.`)
      } else if (status === 'error') {
        this.$message.error(`${info.file.name} file upload failed.`)
      }
    },
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      this.fileList = fileList
    },
  },
}
</script>
